# -*- coding: utf-8 -*-
import sys
import os
import re
from PyQt4 import QtCore, QtGui,QtWebKit
from edit_ui import Ui_templatetool
import win32clipboard
import traceback 
class data:
    templatePath = ''
    templatesDirPath = ''
class tButton(QtGui.QRadioButton):
    def __init__(self, name, parent):
        super(tButton, self).__init__(parent)
        self.setText(name.split('.')[0])
        self.templateName = name
    def mousePressEvent(self,event):
        self.setChecked(True)
        data.templatePath = os.path.join(data.templatesDirPath,self.templateName)
class edit(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_templatetool()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.copy,QtCore.SIGNAL("clicked()"), self.copy)
        QtCore.QObject.connect(self.ui.clear_bn,QtCore.SIGNAL("clicked()"), self.clear)
        self.buttonGroup = QtGui.QButtonGroup()
        self.tnum=2
        data.templatesDirPath = os.path.join(sys.path[0],"template")
        self.setWindowIcon(QtGui.QIcon('i.png'))
        for t in os.listdir(data.templatesDirPath):
            if os.path.splitext(t)[1] != '.html':continue
            self.tnum = self.tnum + 1
            self.templateButton(t)
    def templateButton(self,name):
        self.tButton=tButton(name,self)
        self.ui.gridLayout.addWidget(self.tButton, self.tnum, 1, 1, 1)
        self.buttonGroup.addButton(self.tButton)
        self.tButton.show()
    def title(self):
        title = self.ui.input_alt.text()
        return title
    def image(self):
        url = self.ui.input_url.text()
        alt = self.ui.input_alt.text()
        if url[0:4]=='http':
            img = "<p align='center'><img src='{0}' alt='{1}'></p>".format(url,alt)
        elif url != '':
            img = ''
            number = 1
            quantity=self.ui.imagesNumber.value()
            while quantity:
                img = img + "<p align='center'><img src='http://p.dayintou.com/z/{0}/{1}-{2}.jpg' alt='{3}'></p><hr>".format(url,url,number,alt)
                number = number + 1
                quantity = quantity - 1
        else:
            img = ''
        return img
    def info(self):
        self.ui.input_p.page().mainFrame().evaluateJavaScript("function getcode(){var oEditor=CKEDITOR.instances.editor1;return oEditor.getData();};")
        ss = self.ui.input_p.page().mainFrame().evaluateJavaScript("getcode();")
        return ss
    def copy2clipboard(self,aString):
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardText(aString)
        win32clipboard.CloseClipboard()
    def copy(self):
        with open(data.templatePath, 'r') as sfile:
            s = sfile.read()
        nameList = re.finditer(r'{{.*?}}',s)
        for x in nameList:
            s = re.sub(x.group(), getattr(self,x.group()[2:-2])(), s)
        self.copy2clipboard(s)
        self.ui.message.setText('Copy success !')
        with open("temp.html", 'w') as wfile:
            wfile.write(s)
    def clear(self):
        self.ui.input_p.page().mainFrame().evaluateJavaScript("function clearpage(){var oEditor=CKEDITOR.instances.editor1;oEditor.setData('');};clearpage();")
        self.ui.input_url.clear()
        self.ui.input_alt.clear()
        self.ui.message.setText('Clear success !')
def main():
    os.chdir(sys.path[0])
    print(sys.path[0])
    app = QtGui.QApplication(sys.argv)
    myapp = edit()
    myapp.show()
    sys.exit(app.exec_())
if __name__ == "__main__":
    main()
